package textdiff {
	import mx.collections.ArrayCollection;
	

	/**
	 * Insert a block new lines into the old file.
	 */
	public class InsertCommand extends EditCommand {
		
	    public function InsertCommand(oldFileInfo:FileInfo=null, newFileInfo:FileInfo=null) {
	        super( oldFileInfo, newFileInfo );
	        command = "Insert before";
	        if (newFileInfo != null) {
		        newLines = newFileInfo.nextBlock();
		        newLines.reportable = true;
		    }
	        if (oldFileInfo != null) {
		        oldLines = oldFileInfo.getBlockAt( oldFileInfo.lineNum );
	        }
	    }

	    public override function toEditScript(): String {
	    	var s:String = oldLines.fromLineNum + "i\r" + newLines.textLines + ".\r";
	    	return s;
	    }

		/**
		 * @see textdiff.EditCommand.editText(Array,int):Array
		 */
	    public override function editText(t:Array, offset:int=0): Array {
	    	// make a copy of the input array t
	    	var lines:ArrayCollection = new ArrayCollection(t.slice());
	    	var insertPos:int;
	    	//offset=0;
	    	
	    	// if needed, increase the length of the result array to a size that fits the result, 
	    	// taking the start offset into account
	    	while (lines.length < oldLines.fromLineNum+newLines.lines.length+offset) lines.addItem(""); 
	    	
	    	for (var i:int=0; i<newLines.lines.length; i++) {
	    		insertPos = oldLines.fromLineNum+i+offset;
	    		// is the insert position beyond the length of the original string array?
	    		if (insertPos >= t.length) {
	    			// we have prepared for this situation, because we grew a large enough array,
	    			// so there is an empty slot at the insert position that we can safely replace 
	    			lines.setItemAt(newLines.lines[i], insertPos);
	    		}
	    		else {
	    			// insert the current line ate the insert position
	    			lines.addItemAt(newLines.lines[i], insertPos);
	    		}
	    	}
	    	return lines.toArray();
	    }

	    public override function get fromLineNum(): int { return oldLines.fromLineNum; }
	    public override function get thruLineNum(): int { return oldLines.thruLineNum; }
	}
}